package com.myflink.day03;

import com.myflink.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.ConnectedStreams;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoMapFunction;

import java.util.Arrays;

/**
 * @author Shelly An
 * @create 2020/9/18 10:06
 */
public class Transform_Connect {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> fileDS = env.readTextFile("input/sensor-data.log");
        SingleOutputStreamOperator<WaterSensor> sensorDS = fileDS.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] datas = value.split(",");
                //开发中，用包装类多一些。 parse返回的是基本类型
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
            }
        });

        //再获取一条流
        DataStreamSource<Integer> numDS = env.fromCollection(Arrays.asList(1, 2, 3, 4));

        //使用connect连接两条流，两条流的数据类型可以不一样，因为是同床异梦  <WaterSensor, Integer>
        //只能两条流（DataStreamSource）进行连接
        ConnectedStreams<WaterSensor, Integer> sensorNumDS = sensorDS.connect(numDS);

        SingleOutputStreamOperator<Object> resultDS = sensorNumDS.map(new CoMapFunction<WaterSensor, Integer, Object>() {
            //调用的是1
            @Override
            public String map1(WaterSensor value) throws Exception {
                return value.toString();
            }

            //作为参数的是2
            @Override
            public Integer map2(Integer value) throws Exception {
                return value + 10;
            }
        });

        resultDS.print();

        env.execute();
    }
}
